package com.xmx.ndmallwxapi.utils;

import cn.hutool.core.util.CharUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.xmx.common.utils.R;
import com.xmx.ndmallwxapi.feign.MallFeignClient;
import com.xmx.ndmallwxapi.vo.mall.Storage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.CharUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Random;


@Component

public class TencentUtil {

    @Value("${tengxun.bucketName}")
    private  String bucketName;

    @Value("${tengxun.bucket}")
    private  String bucket;

    @Value("${tengxun.accessKey}")
    private  String accessKey;

    @Value("${tengxun.secretKey}")
    private  String secretKey;

    @Value("${tengxun.path}")
    private  String path;

    @Value("${tengxun.qianzui}")
    private  String qianzui;

    @Resource
    MallFeignClient mallFeignClient;


    /**
     * 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口 大文件上传请参照 API 文档高级 API 上传
     *
     * @param localfile 要上传的文件
     */
    public  String uploadfile(File localfile, String pathPrefix){
        // 1 初始化用户身份信息(secretId, secretKey，可在[腾讯云](https://l.gushuji.site/tencent)后台中的API密钥管理中查看！
          COSCredentials cred = new BasicCOSCredentials(accessKey,secretKey);
        // 2 设置bucket的区域, COS地域的简称请参照
        //    // https://cloud.tencent.com/document/product/436/6224，根据自己创建的存储桶选择地区
        ClientConfig clientConfig = new ClientConfig(new Region(bucket));
        COSClient cosClient = new COSClient(cred,clientConfig);
        String fileName = "";
        try {
            fileName =localfile.getName();
            String subString = fileName.substring(fileName.lastIndexOf("."));
            Random random = new Random();
            // 指定要上传到 COS 上的路径
            fileName = pathPrefix+"/"+random.nextInt(10000)+System.currentTimeMillis()+subString;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,fileName,localfile);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 关闭客户端(关闭后台线程)
            cosClient.shutdown();
        }
        return fileName;
    }

    /**
     *
     * @param inputStream 文件输入流
     * @param contentLength 文件大小
     * @param contentType 文件类型
     * @param keyName 文件名（文件标识）
     * @return
     */
    public R store(InputStream inputStream, long contentLength, String contentType, String keyName){
        /**
         * 设置上传目标
         */
        COSCredentials cred = new BasicCOSCredentials(accessKey,secretKey);
        // 2 设置bucket的区域, COS地域的简称请参照
        //    // https://cloud.tencent.com/document/product/436/6224，根据自己创建的存储桶选择地区
        ClientConfig clientConfig = new ClientConfig(new Region(bucket));
        COSClient cosClient = new COSClient(cred,clientConfig);

        /**
         表示使用Qcloud COS存储的对象元数据。这包括自定义用户提供的元数据，以及Qcloud COS发送和接收的标准HTTP头
         */
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(contentLength);
        objectMetadata.setContentType(contentType);

        //上传关键代码：
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, inputStream, objectMetadata);
        cosClient.putObject(putObjectRequest);

        /**
         * 将上传信息保存至数据库
         */
        String  fileName = path+"/"+ keyName;
        String name = generateKey(keyName);
        Storage storage = new Storage();
        storage.setKey(keyName);
        storage.setName(name);
        Integer i = Integer.valueOf(String.valueOf(contentLength));
        storage.setSize(i);
        storage.setType(contentType);
        storage.setUrl(fileName);
        R save = mallFeignClient.save(storage);

        return save;
    }

    public void  downfile(HttpServletRequest request, HttpServletResponse response, @PathVariable("key")String key) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        // 1 初始化用户身份信息(secretId, secretKey，可在[腾讯云](https://l.gushuji.site/tencent)后台中的API密钥管理中查看！
        COSCredentials cred = new BasicCOSCredentials(accessKey,secretKey);
        // 2 设置bucket的区域, COS地域的简称请参照
        //    // https://cloud.tencent.com/document/product/436/6224，根据自己创建的存储桶选择地区
        ClientConfig clientConfig = new ClientConfig(new Region(bucket));
        COSClient cosClient = new COSClient(cred,clientConfig);
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
// 限流使用的单位是 bit/s, 这里设置下载带宽限制为10MB/s
        getObjectRequest.setTrafficLimit(80*1024*1024);
        COSObject cosObject = cosClient.getObject(getObjectRequest);
        COSObjectInputStream fileInputStream = cosObject.getObjectContent();
        OutputStream outputStream = response.getOutputStream();
        response.reset();
        response.setContentType("application/x-msdownload;charset=utf-8");
        // 设置响应头，控制浏览器下载该文件
        response.setHeader("content-disposition", "attachment;filename="
                + URLEncoder.encode(key, "UTF-8"));
//        FileInputStream fileInputStream = new FileInputStream(cosObjectInput.);

        BufferedOutputStream bos = new BufferedOutputStream(outputStream);

        byte[] bytes = new byte[1024];
        int end = -1;
        while ((end=fileInputStream.read(bytes))>0){
            bos.write(bytes,0,end);
            bos.flush();
        }
        fileInputStream.close();
        outputStream.close();
        bos.close();

    }


    /**
     * 删除文件
     */
    public  void deletefile(String key) throws CosClientException, CosServiceException {
        // 1 初始化用户身份信息(secretId, secretKey，可在[腾讯云](https://l.gushuji.site/tencent)后台中的API密钥管理中查看！
          COSCredentials cred = new BasicCOSCredentials(accessKey,secretKey);
        // 2 设置bucket的区域, COS地域的简称请参照
        //    // https://cloud.tencent.com/document/product/436/6224，根据自己创建的存储桶选择地区
          ClientConfig clientConfig = new ClientConfig(new Region(bucket));
        // 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // 指定要删除的 bucket 和路径
        cosclient.deleteObject(bucketName, key);
        // 关闭客户端(关闭后台线程)
        cosclient.shutdown();
    }


    public org.springframework.core.io.Resource loadPictrue(String keyname){
        try {
            URL url = new URL(path+"/"+keyname);
            org.springframework.core.io.Resource resource = new UrlResource(url);
            if (resource.exists() || resource.isReadable()){
                return resource;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String generateKey(String originalFilename) {
        int index = originalFilename.lastIndexOf('.');
        String suffix = originalFilename.substring(index);

        String key = null;
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 20; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
            key =  sb.toString()+suffix;

        return key;
    }

}
